//
//  BaseRequest.m
//  CoolTennisBall
//
//  Created by Coollang on 16/12/8.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "YFBaseRequest.h"
#import "YFNetError.h"
#import "User.h"
#import "AESCipher.h"


#define         AES_KEY        @"jWFamrZVTIsZvyiJ"

@interface YFBaseRequest ()
    
@end

@implementation YFBaseRequest

- (NSString *)requestUrl {
    return [YFBaseRequest requestString:self.apiType];
}

- (id)responseInfo{
    return [[self responseJSONObject] objectForKey:@"errDesc"];
}


- (id)requestArgument {
    return self.requestArgumentParma ? self.requestArgumentParma:nil;
}

- (YTKRequestMethod)requestMethod {
    return YTKRequestMethodPOST;
}

- (NSInteger)cacheTimeInSeconds {
    return 8;
}

+ (instancetype)requestApiWithType:(RequestApiType)apiType andParam:(id)param {
    YFBaseRequest *api = [[self alloc] init];
    api.apiType = apiType;
    api.requestArgumentParma = param;
    return api;
}

- (NSError *)disposeRequestErrorWithRet:(NSString *)ret {
    return [YFNetError creatErrorWithRet:[YFNetError WebRespondTypeWithRet:ret]];
}

+ (NSString *)requestString:(RequestApiType)apiType {
    switch (apiType) {
//            七牛
        case kGetQiNiuUpHeadIconTokenApi:
            return @"MemberCon/getUpToken";
        case kGetQiNiuUploadImageToMomentApi:
            return @"Sns/getUpToken";
//            登录
        case kLoginEmailSignInApi:
            return @"LoginCon/emailLogin";
        case kLoginEmailSignUpApi:
            return @"LoginCon/emailRegister";
        case kSaveUserInfoApi:
            return @"MemberCon/saveUserInfo";
        case kGetUserInfoApi:
            return @"MemberCon/getUserInfo";
         case kUserFeedbackApi:
            return @"Feedbacks/addFeedBack";
        case kFaceBookLoginApi:
            return @"LoginCon/facebookLogin";
        case kGoogleLoginApi:
            return @"";
        case kLoginForgotpasswordApi:
            return @"MemberCon/getMyPwd";
//            视频
        case kGetVideoStarListApi:
            return @"VideoCon/getVideoNodes";
        case kGetVideoListForIDApi:
            return @"VideoCon/getVideosByID";
//            朋友圈
        case kMomentsGetTopicList:
            return @"Sns/getPostList";
        case kMomentsPostTopic:
            return @"Sns/post";
        case kMomentPostCommentResponse:
            return @"Sns/response";
        case kMomentsTopicLike:
            return @"Sns/postLike";
        case kMomentsCancelTopicLike:
            return @"Sns/delPostLike";
        case kMomentsDeleteTopic:
            return @"Sns/delPost";
        case kMomentsDeleteComment:
            return @"Sns/delPostResponse";
        case kMomentsSpotterTopic:
            return @"Sns/spotter";
        case kMomentGetMessageCount:
            return @"Sns/getMsgCount";
        case kMomentGetMessageList:
            return @"Sns/getMsgList";
        case kMomentDeleteMessage:
            return @"Sns/delMsg";
        case kMomentDeleteAllMessage:
            return @"Sns/delAllMsg";
        case kMomentGetTopicDetial:
            return @"Sns/getPostInfo";
//           俱乐部
        case kClubCreatClub:
            return @"ClubCon/createClub";
        case kClubCreatEvent:
            return @"ClubCon/createClubNews";
        case kClubFind:
            return @"ClubCon/getClubList";
        case kClubSearchClub:
            return @"ClubCon/searchClub";
        case kClubInfo:
            return @"ClubCon/getClubInfo";
        case kClubMessageList:
            return @"ClubCon/getClubMsgList";
        case kClubTargetSet:
            return @"ClubCon/setClubTarget";
        case kClubMemberRanking:
            return @"ClubCon/getClubMemberRanking";
        case kClubMemberDetail:
            return @"ClubCon/getClubMemberDetail";
        case kClubSendMessage:
            return @"ClubCon/postMsg";
        case kClubEventList:
            return @"ClubCon/getClubNewsList";
        case kClubSetPassword:
            return @"ClubCon/setClubPwd";
        case kClubJoinClub:
            return @"ClubCon/joinClub";
        case kClubMemberRank:
            return @"ClubCon/getClubMemberRanking";
        case kClubMyReportList:
            return @"ClubCon/getMyReport";
        case kClubReportMemberList:
            return @"ClubCon/getClubMemberList";
        case kClubReportWeeklyDetail:
            return @"ClubCon/getUserWeeklyStatistics";
        case kClubReportCoachCommentUser:
            return @"ClubCon/addCoachReview";
        case kClubReportGetMyCoachComment:
            return @"ClubCon/getCoachReview";
        case kClubReportWeeklyDetailPro:
            return @"ClubCon/getUserWeeklyReport";
        case kClubQuitClub:
            return @"ClubCon/quitClub";
        case kClubEditClubInformation:
            return @"ClubCon/updateClub";
        case kClubDeleteClubMessage:
            return @"ClubCon/delMsg";
        case kClubDeleteClubEvent:
            return @"ClubCon/delEvent";
        case kClubSpotterClubOrMessage:
            return @"clubCon/spotterClub";
            
//        硬件及运动相关（130-159）
        case kDeviceGetDeviceVersion:
            return @"VersionCon/getFirmwareVersion";
        case kSportUploadDaySportData:
            return @"SportCon/uploadMainData";
        case kSportUploadDayDetailSportData:
            return @"SportCon/uploadSportDetail";
        case kSportGetDayStatisticsSportData:
            return @"SportCon/getSportInfoByDate";
        case kSportGetDayDetailSportData:
            return @"SportCon/getSportDayDetail";
        case kSportGetHaveSportDataDays:
            return @"SportCon/getActiveSportDays";
        case kSportGetWeekStaticsisData:
            return @"SportCon/getWeekDataStatistics";
        case kSportGetMonthStaticsisData:
            return @"SportCon/getMonthStatistics";
        case kSportGetYearStaticsisData:
            return @"SportCon/getYearStatistics";
        case kSportUploadTemplateToServer:
            return @"TemplateCon/uploadTpl";
        case kSportDeleteTemplateToServer:
            return @"TemplateCon/delTpl";
        default:
            break;
    }
}

@end

@implementation YFUrlArgumentsFilter {
    NSDictionary *_arguments;
}

+ (YFUrlArgumentsFilter *)filterWithArguments:(NSDictionary *)arguments {
    return [[YFUrlArgumentsFilter alloc] initWithArguments:arguments];
}
- (id)initWithArguments:(NSDictionary *)arguments {
    self = [super init];
    if (self) {
        _arguments = arguments;
    }
    return self;
}

- (NSString *)filterUrl:(NSString *)originUrl withRequest:(YFBaseRequest *)request {
    return [self urlStringWithOriginUrlString:originUrl withRequest:request appendParameters:_arguments];
}

- (NSString *)urlStringWithOriginUrlString:(NSString *)originUrlString withRequest:(YFBaseRequest *)request appendParameters:(NSDictionary *)parameters {
    
    NSString *paraUrlString = AFQueryStringFromParameters(parameters);
    if (!(paraUrlString.length > 0)) {
        return originUrlString;
    }
    if (request.apiType == kLoginEmailSignUpApi ||
        request.apiType == kLoginEmailSignInApi ||
        request.apiType == kFaceBookLoginApi ||
        request.apiType == kGoogleLoginApi) {
        // 不需要加密签名的请求
        return originUrlString;
    }
    // 增加加密操作
    NSString *path = [YFUrlArgumentsFilter creatPathWithAPI:originUrlString];
    return path;
}

/**
 *  @brief                   生成带签名path
 *
 *  @param api               接口
 *********************************************/
+ (NSString *)creatPathWithAPI:(NSString *)api {
    NSString *timeStamp = [[NSDate date] unixTimeStampWithDateStr];
    User *user = [User getLastUser];
    NSString *sign = [self creatSignWithAPI:api user:user timeStamp:timeStamp];
    NSString *path = [NSString stringWithFormat:@"%@?sign=%@&uid=%@&timestamp=%@",api,sign,user.userID,timeStamp];
    return path;
}

/**
 *  @brief                   生成签名
 *
 *  @param api               接口
 *  @param user              用户
 *  @param timeStamp         时间戳
 *********************************************/
+ (NSString *)creatSignWithAPI:(NSString *)api
                          user:(User *)user
                     timeStamp:(NSString *)timeStamp {
    NSString *token = [AESCipher decryptAES:user.token key:AES_KEY];
    NSString *sign = [NSString stringWithFormat:@"%@&uid=%@&timestamp=%@&token=%@",api,user.userID,timeStamp,token];
    sign = [sign stringToMD5];
    sign = [sign substringWithRange:NSMakeRange(2, 28)];
    sign = [sign stringToMD5];
    return sign;
}

@end

@implementation YFUrlCacheDirPathFilter

- (id)initWithUserId:(NSString *)userId {
    if (self = [super init]) {
        _userId = userId;
    }
    return self;
}

+ (YFUrlCacheDirPathFilter *)filterWithArguments:(NSString *)userId {
   return [[YFUrlCacheDirPathFilter alloc] initWithUserId:userId];
}

// 切换用户z则使用不同的缓存配置文件
- (NSString *)filterCacheDirPath:(NSString *)originPath withRequest:(YTKBaseRequest *)request {
    return originPath;
}

@end

